package com.cardone.context;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 上下文支持
 *
 * @author yaohaitao
 */
@Slf4j
public class ContextHolder implements ApplicationContextAware {
    private ContextHolder() {
    }

    private static ContextHolder contextHolder = new ContextHolder();

    /**
     * Spring ApplicationContext
     */
    @Setter
    @Getter
    private ApplicationContext springApplicationContext;

    public static ApplicationContext getApplicationContext() {
        return contextHolder.getSpringApplicationContext();
    }

    /**
     * 获取 bean
     *
     * @param requiredType 类型
     * @return bean
     */
    public static <T> T getBean(final Class<T> requiredType) {
        return ContextHolder.getBean(requiredType, requiredType.getName());
    }

    /**
     * 获取 bean
     *
     * @param name         名称
     * @param requiredType 类型
     * @return bean
     */
    public static <T> T getBean(final Class<T> requiredType, final String name) {
        if (contextHolder.getSpringApplicationContext() == null) {
            return null;
        }

        if (!contextHolder.getSpringApplicationContext().containsBean(name)) {
            return null;
        }

        return contextHolder.getSpringApplicationContext().getBean(name, requiredType);
    }

    /**
     * 获取 bean
     *
     * @param name 名称
     * @return bean
     */
    public static Object getBean(final String name) {
        if (contextHolder.getSpringApplicationContext() == null) {
            return null;
        }

        if (!contextHolder.getSpringApplicationContext().containsBean(name)) {
            return null;
        }

        return contextHolder.getSpringApplicationContext().getBean(name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        contextHolder.setSpringApplicationContext(applicationContext);
    }
}
